<?php

namespace app\logic\platform;

use app\facade\WebsocketClient;
use app\queue\OrderPush;
use app\model\{WeimengOrder,WeimengOrderGoods};
use think\facade\Log;
use think\facade\Queue;

class Weimeng extends BasePlatform
{
    public function pullProcess(int $start_time, int $end_time) : bool
    {
        $params = compact('start_time', 'end_time');
        $params['limit'] = 100;
        $page = 1;
        do {
            $params['page'] = $page;
            $order_ret = app()->make(\app\logic\api\platform\Weimeng::class, [$this->shop])->pullOrder($params);
            if ($order_ret['code'] != 200) {
                Log::error('微盟订单下载出错：' . $order_ret['message'] . ',入参:' . var_export($params, true));
                return false;
            }
            if (empty($order_ret['data']['pageList'])) {
                break;
            }
            $order_data = $order_ret['data'];
            $page_total = ceil($order_data['totalCount'] / $order_data['pageSize']);
            $this->saveOrder($order_data['pageList']);
        } while(++$page <= $page_total);
        return true;
    }

    /**
     * 保存订单数据并推送到队列
     * @param array $data 订单数据
    */
    private function saveOrder(array $data) : void {
        if (empty($data)) {
            return;
        }
        $order_list = $order_no_arr = [];
        $time_fields = [
            'deliveryTime','paymentTime','updateTime','createTime','confirmReceivedTime'
        ];
        //组合订单数据
        foreach ($data as $k => $v) {
            $order_no = $v['orderNo'];
            //移除数据库中不存在的字段
            unset($v['goodsPromotionInfo'],$v['deliveryDetail'],$v['operationList']);

            //十三位时间戳转换成10位
            foreach ($time_fields as $field) {
                isset($v[$field]) && $v[$field] /= 1000;
            }
            foreach ($v['itemList'] as $_k => $_v) {
                unset($_v['goodsDiscountInfo'],$_v['bizInfo'],$_v['tagInfo'],$_v['baseDiscountInfo'],$_v['bizInfoList']);
                $_v['orderNo'] = $order_no;
                $v['itemList'][$_k] = $_v;
            }
            //保存订单号
            $order_no_arr[] = $v['orderNo'];
            //追加客户Id
            $v['customer_id'] = $this->shop->customer_id;
            //追加商店id
            $v['shop_id'] = $this->shop->id;
            $order_list[] = $v;
        }
        $find_list = WeimengOrder::field('orderNo')->whereIn('orderNo', $order_no_arr)->column('orderNo');
        foreach ($order_list as $k => $v) {
            $order_no = $v['orderNo'];
            //查询下载的订单是否在数据库中已存在
            if (in_array($order_no, $find_list)) {
                continue;
            }
            //订单插入数据库
            app()->db->transaction(function ($query) use($v) {
                $weimeng_order = new WeimengOrder();
                $weimeng_order->strict(false)->save($v);
                $pid = $weimeng_order->getLastInsID();
                $v['itemList'] = array_map(function ($item) use ($pid) {
                    $item['pid'] = $pid;
                    return $item;
                }, $v['itemList']);
                WeimengOrderGoods::strict(false)->insertAll($v['itemList']);

                //添加订单数据到待推送队列中
                $async_data = [
                    'action' => 'pushOrder',
                    'params' => [
                        'type' => 'weimeng',
                        'data' => $v
                    ]
                ];
                WebsocketClient::send(json_encode($async_data));
//                Queue::push(OrderPush::class . '@fire', $queue_data, $queue = null);
            });
        }
    }
}
